package com.example.videoeditor.service;

import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

@Service
public class VideoService {

    public String processVideo(File file, double adTime) throws IOException, InterruptedException {
        String baseName = file.getName().substring(0, file.getName().lastIndexOf('.'));
        String outputFileName = baseName + "_yx.mp4";
        String outputPath = file.getParent() + File.separator + outputFileName;

        // 检查文件是否已经存在并删除
        File outputFile = new File(outputPath);
        if (outputFile.exists() && !outputFile.delete()) {
            return "无法删除已存在的文件: " + outputFileName;
        }

        // 获取视频时长
        String[] durationCommand = {"ffmpeg", "-i", file.getAbsolutePath()};
        Process durationProcess = Runtime.getRuntime().exec(durationCommand);
        BufferedReader stdError = new BufferedReader(new InputStreamReader(durationProcess.getErrorStream()));
        String line;
        String duration = null;
        while ((line = stdError.readLine()) != null) {
            if (line.contains("Duration:")) {
                duration = line.substring(line.indexOf("Duration:") + 10, line.indexOf(", start:")).trim();
                break;
            }
        }
        durationProcess.waitFor();
        if (duration == null) {
            return "无法获取视频时长: " + file.getName();
        }

        // 解析时长
        String[] parts = duration.split(":");
        int hours = Integer.parseInt(parts[0]);
        int minutes = Integer.parseInt(parts[1]);
        double seconds = Double.parseDouble(parts[2]);
        double totalSeconds = hours * 3600 + minutes * 60 + seconds;

        // 计算新的结束时间
        double newEndTime = totalSeconds - adTime;
        if (newEndTime <= 0) {
            return "广告时间超过视频时长: " + file.getName();
        }

        // 构建命令
        String[] command = {
                "ffmpeg", "-i", file.getAbsolutePath(), "-to", String.format("%.3f", newEndTime), "-c", "copy", outputPath};

        ProcessBuilder processBuilder = new ProcessBuilder(command);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));

        StringBuilder output = new StringBuilder();
        String s;
        while ((s = stdInput.readLine()) != null) {
            output.append(s).append("\n");
        }

        int exitCode = process.waitFor();
        if (exitCode == 0) {
            return "处理完成: " + file.getName();
        } else {
            return "处理视频时出错: " + file.getName() + "\n" + output;
        }
    }
}
